package org.example.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.common.constants.Result;
import org.example.dto.LoginDTO;
import org.example.pojo.UserInfo;
import org.example.service.impl.UserInfoServiceImpl;
import org.example.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class AuthController {


    @Autowired
    private UserInfoServiceImpl userInfoService;

    @Autowired
    RedisUtil redisUtil;


    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginDTO loginDTO, HttpServletResponse response) {
        UserInfo user = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("username", loginDTO.getUsername()).eq("password", loginDTO.getPassword()));
        if (user == null) {
            return Result.error("用户名或密码错误");
        }

        // 生成 token（可改为 JWT）
        String token = UUID.randomUUID().toString();

        // 存入 Redis
        String redisKey = "login:user:" + token;
//        redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(user), 30, TimeUnit.MINUTES);
        redisUtil.set(redisKey, JSON.toJSONString(user), 30);

        // 返回 token
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("role", user.getRole());
        return Result.success(map);
    }

    @PostMapping("/logout")
    public Result<?> logout(@RequestHeader("Authorization") String token) {
        redisUtil.delete("login:user:" + token);
        return Result.success("已退出登录");
    }
}